package com.ruihang.generalibrary.utils;

import android.text.TextUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2017/7/7.
 */

public class ClassUtils {

    public static Object getDeclaredField(Object obj, String fieldName) throws Exception {
        if (obj == null || TextUtils.isEmpty(fieldName)) {
            return null;
        }
        Field f = obj.getClass().getDeclaredField(fieldName);
        f.setAccessible(true);
        return f.get(obj);
    }

    public static Object getSuperDeclaredField(Object obj, String fieldName) throws Exception {
        if (obj == null || TextUtils.isEmpty(fieldName)) {
            return null;
        }
        Field f = obj.getClass().getSuperclass().getDeclaredField(fieldName);
        f.setAccessible(true);
        return f.get(obj);
    }

    public static Object getField(Object obj, String fieldName) throws Exception {
        if (obj == null || TextUtils.isEmpty(fieldName)) {
            return null;
        }
        Field f = obj.getClass().getField(fieldName);
        f.setAccessible(true);
        return f.get(obj);
    }

    /**
     * 目前最多支持2个参数
     *
     * @param obj
     * @param methodName
     * @param filed
     * @return
     */
    public static Object invokeMethod(Object obj, String methodName, Object... filed) throws Exception {
        Object re = null;
        if (obj == null || TextUtils.isEmpty(methodName)) {
            return "Error";
        }
        Method me = null;
        boolean noParam=filed == null || filed.length == 0;
        if (noParam) {
            me = obj.getClass().getMethod(methodName);
        } else {
            Class[] css = new Class[filed.length];
            for (int i = 0; i < filed.length; i++) {
                css[i] = filed[i].getClass();
            }
            me = obj.getClass().getMethod(methodName, css);
        }
        me.setAccessible(true);
        if (noParam){
            re=me.invoke(obj);
        }else {
            re = me.invoke(obj, filed);
        }

        return re;
    }

    /**
     * 目前最多支持2个参数
     *
     * @param obj
     * @param methodName
     * @param filed
     * @return
     */
    public static Object invokeSuperMethod(Object obj, String methodName, Object... filed) throws Exception {
        Object re = null;
        if (obj == null || TextUtils.isEmpty(methodName)) {
            return null;
        }
        Method me = null;
        if (filed == null || filed.length == 0) {
            me = obj.getClass().getSuperclass().getMethod(methodName);
        } else {
            Class[] css = new Class[filed.length];
            for (int i = 0; i < filed.length; i++) {
                css[i] = filed[i].getClass();
            }
            me = obj.getClass().getSuperclass().getMethod(methodName, css);
        }
        me.setAccessible(true);
        re = me.invoke(obj, filed);

        return re;
    }
}
